<template>
  <div>
    <div class="header">
      <input type="file" @change="handleChange" />
      <el-button type="primary" @click="print">打印</el-button>
    </div>
    <div class="container" ref="container"></div>
  </div>
</template>

<script setup>
import { renderAsync } from "docx-preview";
import axios from "axios";

const container = ref();

function print() {
  window.print();
}

async function handleChange(e) {
  const file = e.target.files[0];
  const blob = await fileToBlob(file);
  preview(blob);
}

function fileToBlob(file) {
  return new Promise((resolve, reject) => {
    let reader = new FileReader();
    reader.readAsArrayBuffer(file);
    let blob = null;
    reader.onload = (e) => {
      if (typeof e.target.result === "object") {
        blob = new Blob([e.target.result]);
      } else {
        blob = e.target.result;
      }
      resolve(blob);
    };
  });
}

// 支支持docx,xlsx，不支持doc，xls
async function getDoc() {
  const res = await axios({
    url: "http://localhost:8000/doc.docx",
    method: "get",
    responseType: "blob",
  });
  preview(res.data);
}

getDoc();

async function preview(blob) {
  await renderAsync(
    blob, // could be any type that supported by JSZip.loadAsync
    container.value, //element to render document content,
    container.value, //element to render document styles, numbeings, fonts. If null, bodyContainer will be used.
    {
      className: "docx", //class name/prefix for default and document style classes
      inWrapper: true, //enables rendering of wrapper around document content
      ignoreWidth: false, //disables rendering width of page
      ignoreHeight: false, //disables rendering height of page
      ignoreFonts: false, //disables fonts rendering
      breakPages: true, //enables page breaking on page breaks
      ignoreLastRenderedPageBreak: true, //disables page breaking on lastRenderedPageBreak elements
      experimental: false, //enables experimental features (tab stops calculation)
      trimXmlDeclaration: true, //if true, xml declaration will be removed from xml documents before parsing
      useBase64URL: false, //if true, images, fonts, etc. will be converted to base 64 URL, otherwise URL.createObjectURL is used
      useMathMLPolyfill: false, //@deprecated includes MathML polyfills for chrome, edge, etc.
      renderChanges: false, //enables experimental rendering of document changes (inserions/deletions)
      renderHeaders: true, //enables headers rendering
      renderFooters: true, //enables footers rendering
      renderFootnotes: true, //enables footnotes rendering
      renderEndnotes: true, //enables endnotes rendering
      debug: false, //enables additional logging
    },
  );
}
</script>

<style scoped lang="scss">
.header {
  position: fixed;
  left: 20px;
  top: 20px;
}

.container {
  width: 100%;
  //height: 100vh;
}

@media print {
  .header {
    display: none;
  }
}
</style>
